package com.awifi.demo.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    HashMap<String, Channel> channels = new HashMap<>();

    private static ChannelGroup groups = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        groups.writeAndFlush("[客户端]"+channel.remoteAddress()+"加入了聊天室"+"，时间为："+ sdf.format(new Date()));
        groups.add(channel);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        groups.forEach(channel1 -> {
            if (channel1 != channel) {
                channel1.writeAndFlush("[客户端]"+channel1.remoteAddress()+"发送了消息："+ msg +"\n");
            } else {
                System.out.println("[消息回显]"+ channel1.remoteAddress()+":"+msg);
            }
        });
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        groups.writeAndFlush("[客户端]"+channel.remoteAddress()+"离开了聊天室"+"，时间为："+ sdf.format(new Date()));
        groups.remove(channel);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端"+ctx.channel().remoteAddress()+"上线了。。。");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端"+ctx.channel().remoteAddress()+"离线了。。。");
    }
}
